// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 初始化环境

// Haversine公式计算两地距离（单位：米）
function haversine(lat1, lon1, lat2, lon2) {
  const R = 6371e3; // 地球半径（米）
  const φ1 = lat1 * Math.PI / 180; // 转换为弧度
  const φ2 = lat2 * Math.PI / 180;
  const Δφ = (lat2 - lat1) * Math.PI / 180;
  const Δλ = (lon2 - lon1) * Math.PI / 180;

  const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
            Math.cos(φ1) * Math.cos(φ2) * 
            Math.sin(Δλ/2) * Math.sin(Δλ/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  const distance = R * c; // 距离（米）
  return distance;
}

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 关键：将字符串转为数字（必做！）
    const { lat1, lon1, lat2, lon2 } = event;
    const numLat1 = parseFloat(lat1);
    const numLon1 = parseFloat(lon1);
    const numLat2 = parseFloat(lat2);
    const numLon2 = parseFloat(lon2);

    // 校验参数（确保转换后的值有效）
    if (
      isNaN(numLat1) || isNaN(numLon1) || 
      isNaN(numLat2) || isNaN(numLon2)
    ) {
      throw new Error('经纬度参数无效（必须为数字）');
    }

    if (!(-90 <= numLat1 <= 90 || -90 <= numLat2 <= 90 || 
          -180 <= numLon1 <= 180 || -180 <= numLon2 <= 180)) {
      throw new Error('经纬度超出有效范围（纬度：-90~90，经度：-180~180）');
    }

    const distanceMeters = haversine(numLat1, numLon1, numLat2, numLon2);
    const distanceKilometers = (distanceMeters / 1000).toFixed(2);

    return {
      status: 0,
      message: '距离计算成功',
      distance: {
        meters: distanceMeters,
        kilometers: Number(distanceKilometers) // 转为数字，避免字符串
      }
    };
  } catch (error) {
    return {
      status: 1,
      message: error.message || '距离计算失败'
    };
  }
};